package com.feonix.common.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.SimpleScheduleBuilder;

import com.feonix.common.util.StringUtil;

public class TaskScheduleBuilder {
	protected Log logger = LogFactory.getLog(super.getClass());

	private String second = "0";

	private String minute = "0";

	private String hour = "0";

	private String day = "*";

	private String month = "*";

	private String week = "?";

	private String year = "";

	/**
	 * 获得一个任务周期，不可以直接使用，需要设置时间：秒、分钟、小时、天、月、星期、年等， 最后调用getSchedule来获取相应的表达式来使用
	 * 
	 * @return
	 */
	public static TaskScheduleBuilder getInstance() {
		return new TaskScheduleBuilder();
	}

	/**
	 * 获取一个按小时的任务周期，可直接使用
	 * 
	 * @param hours
	 * @return
	 */
	public static Object getEveryHourSchedule(int hours) {
		return SimpleScheduleBuilder.repeatHourlyForever(hours);
	}

	/**
	 * 获取一个按分钟的任务周期，可直接使用
	 * 
	 * @param minutes
	 * @return
	 */
	public static Object getEveryMinuteSchedule(int minutes) {
		return SimpleScheduleBuilder.repeatMinutelyForever(minutes);
	}

	/**
	 * 获取一个按秒的任务周期，可直接使用
	 * 
	 * @param seconds
	 * @return
	 */
	public static Object getEverySecondSchedule(int seconds) {
		return SimpleScheduleBuilder.repeatSecondlyForever(seconds);
	}

	/**
	 * 执行一次
	 * 
	 * @return
	 */
	public static Object getOnceSchedule() {
		return SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0);
	}

	public TaskScheduleBuilder setSecond(String second) {
		this.second = second;
		return this;
	}

	public TaskScheduleBuilder setMinute(String minute) {
		this.minute = minute;
		return this;
	}

	public TaskScheduleBuilder setHour(String hour) {
		this.hour = hour;
		return this;
	}

	public TaskScheduleBuilder setDay(String day) {
		this.day = day;
		this.week = "?";
		return this;
	}

	public TaskScheduleBuilder setMonth(String month) {
		this.month = month;
		return this;
	}

	public TaskScheduleBuilder setWeek(String week) {
		this.week = week;
		this.day = "?";
		return this;
	}

	public TaskScheduleBuilder setYear(String year) {
		this.year = year;
		return this;
	}

	public String getSchedule() {
		StringBuffer schedule = new StringBuffer();
		schedule.append(this.second).append(" ").append(this.minute).append(" ").append(this.hour).append(" ")
				.append(this.day).append(" ").append(this.month).append(" ").append(this.week).append(" ")
				.append(this.year);
		String scheduleStr = schedule.toString().trim();
		StringUtil.cleanStringBuffer(new StringBuffer[] { schedule });
		this.logger.debug("getSchedule:" + scheduleStr);
		return scheduleStr;
	}
}
